package com.xiaozheng.factory;

import com.xiaozheng.service.AccountService;
import com.xiaozheng.utils.TransactionManger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 用于创建Service的代理对象工厂
 * @Package com.xiaozheng.factory
 * @ClassName: BeanFactory
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/10/7 13:36
 * @Description: 描述
 */
public class BeanFactory {

    private AccountService accountService;
    private TransactionManger transactionManger;

    public final void setTransactionManger(TransactionManger transactionManger) {
        this.transactionManger = transactionManger;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public AccountService getAccountService() {
        Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事务的支持
                     * @param proxy
                     * @param method
                     * @param args
                     * @return
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object rtValue = null;
                        try {
                            //1.开启事务
                            transactionManger.begin();
                            //2.执行操作
                            method.invoke(accountService, args);
                            //3.提交事务
                            transactionManger.commit();
                            //4.返回结果
                            return rtValue;
                        } catch (Exception e) {
                            //5.回滚操作
                            transactionManger.rollback();
                            e.printStackTrace();
                        } finally {
                            //6.释放连接
                            transactionManger.release();
                        }
                        return null;
                    }
                });
        return accountService;
    }
}
